import serial
import cc9d
from typing import Callable

class Chhol:    
    def _printd(self, *args, **kwargs):
        if self._do_print:
            print(*args, **kwargs)

    def __init__(self, port, recvPkgCB: Callable[[cc9d.sCc9dPkg], None]):
        self.port = port
        self.ser = None
        self.open()
        self.cc9d = cc9d.CC9DProtocolParser(self._send, recvPkgCB)
        
    def open(self) -> str:
        try:
            self.ser = serial.Serial(self.port, 115200, timeout=1)
            return None
        except serial.SerialException as e:
            return f"无法打开串口 {self.port}: {e}"

    def close(self):
        if self.ser and self.ser.is_open:
            self.ser.close()
    
    def receiveOnce(self):
        if self.ser.in_waiting > 0:
            received_data = self.ser.read(self.ser.in_waiting)
            self.cc9d.receive(received_data)
    
    def sendPkg(self, pkg: cc9d.sCc9dPkg):
        self.cc9d.send(pkg)

    def _send(self, data):
        if self.ser and self.ser.is_open:
            self.ser.write(data)      
            
    def __del__(self):
        self.close_serial()
        print(f"对象 {self.port} 已销毁，串口已关闭")


if __name__ == "__main__":
    import time
    def _receivePkg(pkg: cc9d.sCc9dPkg):
        print(f"收到一个包: {pkg}")
    chhol = Chhol(port='COM54', recvPkgCB=_receivePkg)
    while True:
        chhol.receiveOnce()
        time.sleep(0.05)